package l1j.server.server.model.drop;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.NewSystem.各項記錄輸出;
import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Config;
import l1j.server.Thread.GeneralThreadPool;
import l1j.server.server.model.L1Character;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Quest;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.model.Instance.L1SummonInstance;
import l1j.server.server.model.item.L1ItemId;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.utils.ListMapUtil;
import l1j.server.server.utils.Random;

public class DropShare implements DropShareExecutor {
	private static final Logger _log = Logger.getLogger(DropShare.class.getName());
	// 正向
	private static final byte HEADING_TABLE_X[] = { 0, 1, 1, 1, 0, -1, -1, -1 };

	private static final byte HEADING_TABLE_Y[] = { -1, -1, 0, 1, 1, 1, 0, -1 };

	/**物品掉落特殊訊息*/
	private static final String[] DROP_MSG_MAP = {
		 "\\fM ]\\fC奏下了殺響"
		,"\\fM ]\\fC締造了神話"
		,"\\fM ]\\fC完成了奇蹟"
		,"\\fM ]\\fC奠定了霸業"
		,"\\fM ]\\fC開創了世代"
		,"\\fM ]\\fC超越了傳奇"
		,"\\fM ]\\fC劃下了驚鴻"
	};

	// ドロップを分配
	@Override
	public void dropShare( L1NpcInstance npc, ArrayList<L1Character> acquisitorList, ArrayList<Integer> hateList) {
		DropShareR dropShareR = new DropShareR(npc, acquisitorList, hateList);
		GeneralThreadPool.getInstance().schedule(dropShareR, 0);
	}

	private class DropShareR implements Runnable {
		final L1NpcInstance _npc;
		final ArrayList<L1Character> _acquisitorList;
		final ArrayList<Integer> _hateList;

		private DropShareR(L1NpcInstance npc, ArrayList<L1Character> acquisitorList, ArrayList<Integer> hateList) {
			_npc = npc;
			_acquisitorList = acquisitorList;
			_hateList = hateList;
		}
		@Override
		public void run() {
			try {
				final L1Inventory inventory = _npc.getInventory();
				if(inventory == null){
					return;
				}
				if (inventory.getSize() <= 0) {
					return;
				}
				if (_acquisitorList.size() != _hateList.size()) {
					return;
				}
				// ヘイトの合計を取得
				int totalHate = 0;
				L1Character acquisitor;
				for (int i = _hateList.size() - 1; i >= 0; i--) {
					acquisitor = _acquisitorList.get(i);

					if (Config.AUTO_LOOT == 2 // オートルーティング２の場合はサモン及びペットは省く
							&& (acquisitor instanceof L1SummonInstance || acquisitor instanceof L1PetInstance)) {
						_acquisitorList.remove(i);
						_hateList.remove(i);

					} else if (acquisitor != null 
							&& ((L1PcInstance)acquisitor).getNetConnection()!=null 
							&& acquisitor.getMapId() == _npc.getMapId()
							&& acquisitor.getLocation().getTileLineDistance(_npc.getLocation()) <= Config.LOOTING_RANGE) {
						totalHate += _hateList.get(i);
					} else { // nullだったり死んでたり遠かったら排除
						_acquisitorList.remove(i);
						_hateList.remove(i);
					}
				}

				// ドロップの分配
				//				L1ItemInstance item;
				L1Inventory targetInventory = null;
				L1PcInstance player;
				int randomInt, chanceHate, itemId ;

				//		while(!inventory.isEmpty()){
				final List<L1ItemInstance> list = inventory.getItems();
				if (list.isEmpty()) {
					return;
				}
				if (list.size() <= 0) {
					return;
				}
				//				for (int i = inventory.getSize(); i > 0; i--) {
				//					item = inventory.getItems().get(0);
				for (L1ItemInstance item : list) {
					itemId = item.getItemId();
					boolean isGround = false;
					if (item.getItem().getType2() == 0 && item.getItem().getType() == 2) { // light系アイテム
						item.setNowLighting(false);
					}
					if ( (Config.AUTO_LOOT != 0 || itemId == L1ItemId.ADENA)
							&& totalHate > 0 ) { // オートルーティングかアデナで取得者がいる場合
						randomInt = Random.nextInt(totalHate);
						chanceHate = 0;
						for (int j = _hateList.size() - 1; j >= 0; j--) {
							chanceHate += _hateList.get(j);
							if (chanceHate > randomInt || j<=0) {
								acquisitor = _acquisitorList.get(j);
								if (itemId >= 40131 && itemId <= 40135) {
									if (!(acquisitor instanceof L1PcInstance)|| _hateList.size() > 1) {
										targetInventory = null;
										break;
									}
									player = (L1PcInstance) acquisitor;
									if (player.getQuest().get_step(L1Quest.QUEST_LYRA) != 1) {
										targetInventory = null;
										break;
									}
								}
								if (item.getItem().getBroad()){ // 物品掉落廣播
									if (acquisitor instanceof L1PcInstance) {
										player = (L1PcInstance) acquisitor;
										BraodToAll(player , _npc , item);
									}
								}
								if (acquisitor.getInventory().checkAddItem(item,item.getCount()) == L1Inventory.OK) {
									targetInventory = acquisitor.getInventory();
									if (acquisitor instanceof L1PcInstance) {

										player = (L1PcInstance) acquisitor;

										if( itemId == L1ItemId.ADENA){
											final int newcount = (int) ((_npc.ADENA * player.get金幣率()) + item.getCount());
											item.setCount(newcount);
											final L1ItemInstance l1iteminstance = player.getInventory().findItemId(L1ItemId.ADENA); // 所持アデナをチェック

											if (l1iteminstance != null && l1iteminstance.getCount() + item.getCount() > 2000000000) {
												targetInventory = L1World.getInstance().getInventory(acquisitor.getX(),acquisitor.getY(),acquisitor.getMapId()); // 持てないので足元に落とす
												isGround = true;
												player.sendPackets(new S_ServerMessage(166,"所持有的金幣", "超過2,000,000,000。")); // \f1%0が%4%1%3%2
											}
										}
										if (player.isInParty()) { // 組隊中
											final L1PcInstance[] partyMember = player.getParty().getMembers();
											for (final L1PcInstance element : partyMember) {
												if(element ==player){
													player.sendPackets(new S_ServerMessage(143, _npc.getName(), item.getLogName())); // \f1%0が%1をくれました。
												}else if(element.getConfig().isPartyIfo()){//組隊取得物品資訊 開關
													element.sendPackets(new S_ServerMessage(813, _npc.getName(),item.getLogName(),player.getName()));
												}
											}
										} else {// 沒有組隊
											if(itemId == 90308){ //商城元寶變色aG aF
												player.sendPackets(new S_ServerMessage(143, _npc.getName(), "\\aG"+item.getLogName())); // \f1%0が%1をくれました。
											}else{
												player.sendPackets(new S_ServerMessage(143, _npc.getName(), item.getLogName())); // \f1%0が%1をくれました。
											}
										}
									} else {
										//targetInventory = L1World.getInstance().getInventory(acquisitor.getX(),acquisitor.getY(),acquisitor.getMapId()); // 持てないので足元に落とす
										isGround = true;
									}
									break;
								}
							}
						}
					} else { // ノンオートルーティング
						final List<Integer> dirList = new ArrayList<Integer>();
						for (int j = 0,n=8; j < n; j++) {
							dirList.add(j);
						}
						int x = 0,
								y = 0,
								dir = 0;
						do {
							if (dirList.size() == 0) {
								x = 0;
								y = 0;
								break;
							}
							randomInt = Random.nextInt(dirList.size());
							dir = dirList.get(randomInt);
							dirList.remove(randomInt);
							x = HEADING_TABLE_X[dir];
							y = HEADING_TABLE_Y[dir];
							Thread.sleep(1);
						}

						while (!_npc.getMap().isPassable(_npc.getX(), _npc.getY(), dir));
						targetInventory = L1World.getInstance().getInventory(_npc.getX() + x, _npc.getY() + y, _npc.getMapId());
						ListMapUtil.clear(dirList);
						isGround = true;
					}
					if (itemId >= 40131 && itemId <= 40135) {
						if (isGround || targetInventory == null) {
							inventory.removeItem(item, item.getCount());
							continue;
						}
					}
					if(targetInventory !=null){
						inventory.tradeItem(item, item.getCount(), targetInventory);
					}else{
						inventory.removeItem(item);
					}
				}
				ListMapUtil.clear(list);
				//				_npc.turnOnOffLight();
			}catch(Exception e){
				_log.log(Level.SEVERE, e.getLocalizedMessage() , e);
			} finally {
				// 移除此 ArrayList 中的所有元素
				ListMapUtil.clear(_acquisitorList);
				ListMapUtil.clear(_hateList);
			}
		}
	}

	private void BraodToAll(final L1PcInstance player ,final L1NpcInstance npc , final L1ItemInstance item){
		final String
		npcname = npc.getName() ,
		pcname = player.getName() ,
		itemname = item.getLogName();
		final int itemId = item.getId();
		final StringBuilder msg = new StringBuilder(32);
		msg.append("\\aK[ ").append(pcname).append(" ]降伏了[ ").append(npcname).append(" ]")
		.append("\n").append("\\aK取得[ ").append(itemname).append(DROP_MSG_MAP[Random.nextInt(DROP_MSG_MAP.length)]);
		L1World.getInstance().broadcastPacketToAll(player , new S_SystemMessage(msg.toString()));
		msg.delete(0, msg.length());

		player.sendPackets(new S_SystemMessage("\\fM流水號:["+itemId+"]"));

		final StringBuilder aa=new StringBuilder(32);
		aa.append("IP:(");
		aa.append(player.getNetConnection().getIp().toString());
		aa.append(")帳號【");
		aa.append(player.getAccountName());
		aa.append("】玩家【");
		aa.append(pcname);
		aa.append("】殺死【");
		aa.append(npcname);
		aa.append("】取得		【");
		aa.append(itemname);
		aa.append("】	流水號:[");
		aa.append(itemId);
		aa.append("]	時間:	");
		aa.append(new Timestamp(System.currentTimeMillis()));

		各項記錄輸出.LogSave(17, aa.toString());
		aa.delete(0, aa.length());
	}
}
